package models.base;

import facade.AppContext;
import models.common.BaseModel;
import models.constants.DeletedStatus;
import org.apache.commons.lang.StringUtils;

import javax.persistence.*;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * Created by weiwei on 2018/02/08.
 */
@Entity
@Table(name = "admin_business_operates")
public class AdminBusinessOperate extends BaseModel {
    /**
     * 业务
     */
    @ManyToOne
    @JoinColumn(name = "business_id")
    public AdminBusiness business;

    /**
     * 关联菜单项
     */
    @ManyToOne
    @JoinColumn(name = "menu_id")
    public AdminMenu menuItem;

    @Transient
    public String menuId;


    public AdminBusinessOperate() {

    }

    public static void create(AdminBusiness business,List<AdminBusinessOperate> operateList){
        deleteByBusinessId(business.id);
        if(operateList != null && operateList.size()>0){
            for (AdminBusinessOperate operate : operateList) {
                if(operate.menuId != null){
                    AdminMenu menu = AdminMenu.findOne(operate.menuId);
                    if(menu != null){
                        operate.business = business;
                        operate.menuItem = menu;
                        operate.save();
                    }
                }
            }

        }
    }
    /**
     * 根据业务ID删除业务关联菜单
     *
     * @param businessId
     */
    public static void deleteByBusinessId(String businessId) {
        AdminUser loginUser = AppContext.currentUser();
        List<AdminBusinessOperate> operateList = findByBusinessId(businessId);
        if(operateList.size()>0) {
            for (AdminBusinessOperate operate : operateList) {
                operate.deleted = DeletedStatus.DELETED;
                operate.modifyAt = new Date();
                operate.modifyUser = loginUser;
                operate.save();
            }
        }
    }

    /**
     * 根据业务ID加载业务关联菜单
     *
     * @param businessId
     * @return
     */
    public static List<AdminBusinessOperate> findByBusinessId(String businessId) {
        if(StringUtils.isEmpty(businessId)) return Collections.emptyList();
        return find("deleted=? and business.id = ?", DeletedStatus.UN_DELETED, businessId).fetch();
    }

}
